package com.eden.websocket.config;

import com.eden.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

/**
 * 开启WebSocket支持
 * 协助server获取http session
 */

//@Configuration
//public class WebSocketConfig{
//    @Bean
//    public ServerEndpointExporter serverEndpointExporter()
//    {
//        return new ServerEndpointExporter();
//    }
//}


@Configuration
public class WebSocketConfig extends ServerEndpointConfig.Configurator {
    private static final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        //获取httpsession
        HttpSession session = (HttpSession) request.getHttpSession();
        System.out.println("HttpSession.class.getName():" + HttpSession.class.getName());
        if (StringUtils.isNotNull(session)) {
            System.out.println("获取到session :" + session);
            sec.getUserProperties().put(HttpSession.class.getName(), session);
        }

    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}
